import base64
import json
import re
import os

from meiduo_mall.settings.dev import logger
from utils.secret import SecretOauth
from apps.users.models import User
from django_redis import get_redis_connection
from django.shortcuts import render
from django import http
# Create your views here.
from django.views import View


# 忘记密码的类

class UserNewPasswordView(View):
    def post(self, request, user_id):

        json_dict = json.loads(request.body.decode())
        password = json_dict.get('password')
        password2 = json_dict.get('password2')
        access_token = json_dict.get('access_token')


        if not all([password,password2,access_token]):
            return http.HttpResponseForbidden('参数不能为空!')

        # 解密前端 传入的
        loads_acces_token = SecretOauth().loads(access_token)

        if not re.match('^[0-9A-Za-z]{8,20}$', password):
            return http.HttpResponseForbidden('请输入8-20位的密码')
        # *   3.确认密码: ---------判空,判断是否相等
        if password2 != password:
            return http.HttpResponseForbidden('两次密码输入不一致')


        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return http.JsonResponse({"status": 5002, 'message': "user_id有误!"})

        redis_client = get_redis_connection('verify_image_code')
        redis_random_token = redis_client.get('random_%s' % user.mobile)
        if loads_acces_token != redis_random_token.decode():
            return http.JsonResponse({"status": 5001, 'message': "token错误!"})

        # 更新密码
        user.set_password(password)
        user.save()
        print('第四阶段json_dict的内容', json_dict)
        print('第四阶段password的内容', password)
        print('第四阶段password2的内容', password2)
        print('第四阶段access_token的内容', access_token)
        print('第四阶段loads_acces_token的内容', loads_acces_token)
        print('第四阶段redis_client的内容', redis_client)
        print('第四阶段redis_random_token的内容', redis_random_token)


        return http.JsonResponse({"status": 5000, 'message': "密码设置成功!"})



# 第二步提交
class SecondView(View):
    def get(self, request, mobile):
        sms_code = request.GET.get('sms_code')

        # 1.校验手机号
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist as e:
            logger.error(e)
            return http.JsonResponse({"status": 5004})

        # 2.校验验证码
        sms_client = get_redis_connection('sms_code')
        redis_sms_code = sms_client.get('sms_%s' % mobile)

        if sms_code != redis_sms_code.decode():
            return http.JsonResponse({"status": 5001})

        # 3.返回正确的响应
        redis_client = get_redis_connection('verify_image_code')
        redis_random_token = redis_client.get('random_%s' % mobile)
        access_token = SecretOauth().dumps(redis_random_token.decode())
        print('第三阶段user的内容', user)
        print('第三阶段sms_client的内容', sms_client)
        print('第三阶段redis_sms_code的内容', redis_sms_code)
        print('第三阶段redis_client的内容', redis_client)
        print('第三阶段redis_random_token的内容', redis_random_token)
        print('第三阶段access_token的内容', access_token)

        return http.JsonResponse({"status": 5000, "user_id": user.id, "access_token": access_token})


# 发送短信
class FindPasswordSendSmsCodeView(View):
    def get(self, request, mobile):

        # 1.接收access_token 解密 校验是否准确
        access_token = request.GET.get('access_token')
        # 解密前端 传入的
        loads_acces_token = SecretOauth().loads(access_token)

        # 获取后台存储的
        redis_client = get_redis_connection('verify_image_code')
        redis_random_token = redis_client.get('random_%s' % mobile)
        if loads_acces_token != redis_random_token.decode():
            return http.JsonResponse({"status": 5001, 'message': "token错误!"})

        # * 3.生成随机 6位 短信验证码内容 random.randit()
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        # *   4.存储 随机6位 redis里面(3步 )
        sms_client = get_redis_connection('sms_code')

        # 1.获取 频繁发送短信的 标识
        send_flag = sms_client.get('send_flag_%s' % mobile)

        # 2.判断标识 是否存在
        if send_flag:
            return http.JsonResponse({'code': '4001', 'errmsg': '发送短信过于频繁66'})

        # 3.标识不存在 ,重新倒计时
        p1 = sms_client.pipeline()
        p1.setex('send_flag_%s' % mobile, 60, 1)
        p1.setex('sms_%s' % mobile, 300, sms_code)
        p1.execute()
        # *   5.发短信---第三方容联云--
        print("原始短信:", sms_code)
        # from celery_tasks.sms.tasks import ccp_send_sms_code
        # ccp_send_sms_code.delay(mobile, sms_code)
        #

        # *   6.返回响应对象
        print('第二阶段access_token的内容', access_token)
        print('第二阶段loads_caaes_token的内容', loads_acces_token)
        print('第二阶段redis_client的内容', redis_client)
        print('第二阶段redis_random_token的内容', redis_random_token)
        print('第二阶段randint的内容', randint)
        print('第二阶段sms_code的内容', sms_code)
        print('第二阶段sms_client的内容', sms_client)
        print('第二阶段send_flag的内容', send_flag)
        return http.JsonResponse({"status": 200, 'message': "短信发送成功!"})

class FirstView(View):
    def get(self, request, username):
        # 1.接收参数
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 2.校验用户名 和 图形验证码
        try:
            user = User.objects.get(username=username)
            print('第一阶段user的内容', user)
        except User.DoesNotExist as e :
            logger.error(e)
            print(e)
            return http.JsonResponse({'status': 5004})
        img_client = get_redis_connection('verify_image_code')
        redis_img_code = img_client.get('img_%s' % uuid)

        if image_code.lower() != redis_img_code.decode().lower():
            return http.JsonResponse({'status': 5001})

        # 生成随机64位码字符串 存入redis 为下次发短信提交做准备
        mobile = user.mobile
        random_str = generat_csrf()

        img_client.setex('random_%s' % mobile, 300, random_str)

        access_token = SecretOauth().dumps(random_str)
        print('第一阶段mobile的内容', mobile)
        print('第一阶段random的内容', random_str)
        print('第一阶段img_client的内容', img_client)
        print('第一阶段access_token的内容', access_token)
        # 3.返回响应
        return http.JsonResponse({'status': 5000, "mobile": mobile, "access_token": access_token})



class FindPasswordView(View):
    def get(self,request):
        # 返回忘记密码页面的路由
        return render(request, 'find_password.html')
# 生成 随机码
def generat_csrf():
    return bytes.decode(base64.b64encode(os.urandom(48)))